package com.nit.lab.service.medical.impl;

import com.nit.lab.dto.medical.BedDTO;
import com.nit.lab.dto.utils.PagingDTO;
import com.nit.lab.dto.utils.TableReqDTO;
import com.nit.lab.dto.utils.TableRspDTO;
import com.nit.lab.entity.medical.BedEntity;
import com.nit.lab.mapper.medical.BedMapper;
import com.nit.lab.service.medical.BedService;
import ma.glasnost.orika.MapperFactory;
import ma.glasnost.orika.impl.DefaultMapperFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class BedServiceImpl implements BedService {
    private final BedMapper bedMapper;

    @Autowired(required = false)
    public BedServiceImpl(BedMapper bedMapper) {
        this.bedMapper = bedMapper;
    }

    @Override
    public TableRspDTO list4Table(TableReqDTO tableReqDTO) throws Exception {
        Long count = bedMapper.count4Table(
                tableReqDTO.parseQueryParam("sensorId"));
        PagingDTO pagingDTO = new PagingDTO(
                tableReqDTO.getPageNo(),
                tableReqDTO.getPageSize(),
                count,
                bedMapper.list4Table(
                        tableReqDTO.getStart(),
                        tableReqDTO.getPageSize(),
                        tableReqDTO.parseQueryParam("bedId"),
                        tableReqDTO.parseQueryParam("sensorId"),
                        tableReqDTO.getSortField(),
                        tableReqDTO.getSortOrder()));
        TableRspDTO tableRspDTO = new TableRspDTO(pagingDTO);
        return tableRspDTO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer add(BedDTO bedDTO) throws Exception {
        MapperFactory mapperFactory = new DefaultMapperFactory.Builder().build();
        BedEntity bedEntity = mapperFactory.getMapperFacade().map(bedDTO, BedEntity.class);
        return bedMapper.add(bedEntity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer update(BedDTO bedDTO) throws Exception {
        MapperFactory mapperFactory = new DefaultMapperFactory.Builder().build();
        BedEntity bedEntity = mapperFactory.getMapperFacade().map(bedDTO, BedEntity.class);
        return bedMapper.update(bedEntity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer remove(String bedIds) throws Exception {
        String[] arrayBedId = bedIds.split(",");
        for (int i = 0; i < arrayBedId.length; i++) {
            bedMapper.remove(Long.parseLong(arrayBedId[i]));
        }
        return arrayBedId.length;
    }

    @Override
    public BedDTO getBedById(Long bedId) throws Exception {
        return bedMapper.getBedById(bedId);
    }
}
